﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common;
using ElectrosLtd.Models;
using Common.Views;

namespace ElectrosLtd.Controllers
{
    public class ShoppingCartController : Controller
    {
        //
        // GET: /ShoppingCart/

        public ActionResult MyCart()
        {
            List<ShoppingCartView> userItems = new UsersServ.WCFUsersClient().DisplayShoppingCart(HttpContext.User.Identity.Name).ToList();
            return View("MyCart", userItems);
        }

        
        public ActionResult Purchase()
        {
            List<ShoppingCart> userItems = new UsersServ.WCFUsersClient().ListShoppingCart(HttpContext.User.Identity.Name).ToList();

            if (userItems.Count != 0)
            {
                Order newOrder = new Order();
                OrderDetail newOD = new OrderDetail();

                newOrder.ID = Guid.NewGuid();
                newOrder.Date = DateTime.Now;
                newOrder.Username_FK = HttpContext.User.Identity.Name;

                new UsersServ.WCFUsersClient().AddOrder(newOrder);

                foreach (ShoppingCart noOFSC in userItems)
                {
                    ShoppingCart sc = new UsersServ.WCFUsersClient().GetShoppingCartByID(noOFSC.ID);

                    newOD.Order_FK = newOrder.ID;
                    newOD.Product_FK = sc.Product_FK;
                    newOD.Quantity = sc.Quantity;

                    new UsersServ.WCFUsersClient().AddOrderDetails(newOD);
                    new UsersServ.WCFUsersClient().DeleteCart(sc.ID);                    
                }
                
                return RedirectToAction("MyOrders", "Home");
            }

            return RedirectToAction("MyCart", "ShoppingCart");

        }
       
        public ActionResult Delete()
        {
            List<ShoppingCart> userItems = new UsersServ.WCFUsersClient().ListShoppingCart(HttpContext.User.Identity.Name).ToList();
            
            foreach (ShoppingCart noOFSC in userItems)
            {
                ShoppingCart sc = new UsersServ.WCFUsersClient().GetShoppingCartByID(noOFSC.ID);
                new UsersServ.WCFUsersClient().DeleteCart(sc.ID);
            }
            
            return RedirectToAction("Index", "Home");
        }

    }
}
